package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zero
 * @date 2020/7/3
 */

@Service
public class SearchServiceImpl implements SearchService {


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public Map search(Map<String, String> searchMap) {

        //最终返回结果的map集合
        Map<String,Object> resultMap = new HashMap<>();

        //构建查询
        if (searchMap != null){

            //第一个参数:条件构建对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            //构建多查询条件的封装对象(boolQuery可以拼接多个查询条件)
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //封装第一个条件:关键字查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))){
                boolQuery.must(QueryBuilders.matchQuery("name",searchMap.get("keywords")).operator(Operator.AND));
            }
            //按照品牌进行过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("brand"))){
                boolQuery.filter(QueryBuilders.termQuery("brandName",searchMap.get("brand")));
            }
            //按照规格进行过滤查询
            for (String key : searchMap.keySet()) {
                if (key.startsWith("spec_")){
                    String value = searchMap.get(key).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }

            //按照价格进行区间过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
                if (prices.length == 2){
                    //代表是一个闭合区间  500-1000
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                //代表是开区间  1000以上
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }


            nativeSearchQueryBuilder.withQuery(boolQuery);

            //根据品牌名称进行聚合(分组)查询
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //根据规格进行聚合(分组)查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //开启分页查询
            String pageNum = searchMap.get("pageNum");
            String pageSize = searchMap.get("pageSize");
            if (StringUtils.isEmpty(pageNum)){
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)){
                pageSize = "30";
            }
            //设置分页
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));

            //按照相关字段进行排序查询
            //需要:1.当前域 2.排序方式
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if ("DESC".equals(searchMap.get("sortRule"))){
                    //降序排列
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.DESC));
                }else{
                    //升序排列
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort(searchMap.get("sortField")).order(SortOrder.ASC));
                }
            }

            //设置高亮域
            //设置高亮域的字段
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);

            /**
             * queryForPage()需要三个参数
             * 第一个参数:条件构建对象
             * 第二个参数:查询的实体类
             * 第三个参数:查询结果的操作对象
             */
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                //第三个参数:查询结果的操作对象
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

                    List<T> list = new ArrayList<T>();
                    //封装查询内容数据
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null){
                        for (SearchHit hit : hits) {
                            //将每一条索引库中的hit转换为skuInfo对象
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                            //替换高亮域内容
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0){
                                String highlightField = highlightFields.get("name").fragments()[0].toString();
                                skuInfo.setName(highlightField);
                            }
                            list.add((T) skuInfo);
                        }
                    }
                    //返回数据
                    return new AggregatedPageImpl<T>(list,pageable,hits.getTotalHits(),searchResponse.getAggregations());
                }
            });

            //封装返回的最终结果
            //总记录数
            resultMap.put("total",resultInfo.getTotalElements());
            //总页数
            resultMap.put("totalPages",resultInfo.getTotalPages());
            //数据集合
            resultMap.put("rows",resultInfo.getContent());

            //封装品牌分类数据
            StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
            //流的方式进行封装
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            //品牌集合数据
            resultMap.put("brandList",brandList);

            //封装规格分类数据
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
            //流的方式进行封装
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            //规格数据集合
            resultMap.put("specList",this.formatSpecList(specList));

            //当前页
            resultMap.put("pageNum",pageNum);

            return resultMap;
        }

        return null;
    }

    public Map<String,Set<String>> formatSpecList(List<String> specList){

        //创建map容器
        Map<String,Set<String>> resultMap = new HashMap<>();
        //处理specList数据
        if(specList != null && specList.size() > 0){
            for (String specJsonString : specList) {
                //将json格式转换为map格式
                Map<String,String> specMap = JSON.parseObject(specJsonString, Map.class);
                //遍历
                for (String specKey : specMap.keySet()) {
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet == null){
                        //还没有存储数据,需要创建set集合,存储数据
                        specSet = new HashSet<>();
                    }
                    //已经存储过数据
                    specSet.add(specMap.get(specKey));
                    //封装到resultMap集合中
                    resultMap.put(specKey,specSet);
                }
            }
        }
        return resultMap;
    }
}
